//
//  ZZShareView.m
//  ExpertApp
//
//  Created by zhangxy on 2017/9/7.
//  Copyright © 2017年 sjhz. All rights reserved.
//

#import "ZZShareView.h"
#import "UIButtonUpDown.h"
#import "ReportView.h"
#import "WXApiManager.h"

#import "ZZHomeTopicEntity.h"
#import "SpecialEntity.h"
#import "AppEntity.h"
#import "ForumEntity.h"


#import <UShareUI/UShareUI.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "WXApi.h"



@interface ZZShareView(){
    UIImage *shareImage;
}

@property(nonatomic,strong) UIViewController *curVC;
@property(nonatomic,assign) ZZShareType type;
@property(nonatomic,strong) UIView *bottomView;

@end


@implementation ZZShareView

-(instancetype)initWithShareType:(ZZShareType)type vc:(UIViewController *)vc obj:(id) model{
    
    self = [super initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    if (self)
    {
        _type = type;
        _curVC = vc;
        _shareModel = model;
        self.backgroundColor = UIColor.clearColor;
        
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dissmisMenu)];
        [self addGestureRecognizer:tap];
        
        CGFloat ShareHeight = 217;
        if(_type == ZZShareTypeImage){
            ShareHeight = 110;
        }
        
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(10, SCREEN_HEIGHT-ShareHeight-75, SCREEN_WIDTH-20, ShareHeight)];
        _bottomView.backgroundColor = UIColorFromRGB(0xFCFCFC);
        _bottomView.layer.cornerRadius = 10.0f;
        _bottomView.layer.masksToBounds = YES;
        [self addSubview:_bottomView];
        
        
        [self createShareButton:1 type:1];
        [self createShareButton:2 type:1];
        [self createShareButton:3 type:1];
        [self createShareButton:4 type:1];
        [self createShareButton:5 type:1];
//
//        UIImageView *bgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 110, SCREEN_WIDTH, 1)];
//        [bgView1 setBackgroundColor:UIColorFromRGB(0xDBDBDB)];
//        [_bottomView addSubview:bgView1];
        if(_type != ZZShareTypeImage){
            [self createShareButton:1 type:2];
            [self createShareButton:2 type:2];
        }
        
        if(_type == ZZShareTypeCommunity){
//            CommunityDetail *detail = (CommunityDetail *)_shareModel;
//            User *user = [UserUtil getUser];
//            if(detail.author.uuid == user.uid){
//                [self createShareButton:4 type:2];
//            }
        }
//        else{
//            KnowledgeDetail *detail = (KnowledgeDetail *)_shareModel;
//            if([detail.authorId integerValue] == [UserUtil getUser].uid){
//                [self createShareButton:4 type:2];
//            }
//        }
        
        
//        UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, h-64, SCREEN_WIDTH, 64)];
//        [bgView setBackgroundColor:UIColor.whiteColor];
//        [_bottomView addSubview:bgView];
        
        UIButton *btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnClose setFrame:CGRectMake(10, ScreenHeight - 64, SCREEN_WIDTH - 20, 57)];
        [btnClose setTitle:@"取消" forState:0];
        [btnClose setTitleColor:UIColorFromRGB(Text6Color) forState:0];
        btnClose.layer.cornerRadius = 10.f;
        btnClose.layer.masksToBounds = YES;
        [btnClose setBackgroundColor:UIColorFromRGB(0xFCFCFC)];
        [btnClose addTarget:self action:@selector(dissmisMenu) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btnClose];
    }
    
    return self;
}

-(void)createShareButton:(int) i type:(int) type{
    CGFloat y = 20;
    if(type == 2){
        y = 120;
    }
    CGFloat itemW = (SCREEN_WIDTH-60 - 40-20)/5;
    CGFloat x = 20 + (i-1)*itemW + (i-1)*15;
    UIButtonUpDown *btn = [UIButtonUpDown buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(x-2, y, itemW+4, 78)];
    [btn setTitleColor:DEEP_GRAY_COLOR forState:UIControlStateNormal];
    [btn.titleLabel setFont:FontThirteen];
    [btn addTarget:self action:@selector(shareWithButton:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:btn];
    
    if(type == 1){
        if(i==1){
            [btn setImage:[UIImage imageNamed:@"qq 分享"] forState:UIControlStateNormal];
            [btn setTitle:@"QQ" forState:UIControlStateNormal];
            btn.tag = UMSocialPlatformType_QQ;
        }else if(i==2){
            [btn setImage:[UIImage imageNamed:@"qq空间 分享"] forState:UIControlStateNormal];
            [btn setTitle:@"QQ空间" forState:UIControlStateNormal];
            btn.tag = UMSocialPlatformType_Qzone;
        }else if(i==3){
            [btn setImage:[UIImage imageNamed:@"微信 分享"] forState:UIControlStateNormal];
            [btn setTitle:@"微信好友" forState:UIControlStateNormal];
            btn.tag = UMSocialPlatformType_WechatSession;
        }else if(i==4){
            [btn setImage:[UIImage imageNamed:@"朋友圈 分享"] forState:UIControlStateNormal];
            [btn setTitle:@"朋友圈" forState:UIControlStateNormal];
            btn.tag = UMSocialPlatformType_WechatTimeLine;
        }else if(i==5){
            [btn setImage:[UIImage imageNamed:@"微博 分享"] forState:UIControlStateNormal];
            [btn setTitle:@"微博" forState:UIControlStateNormal];
            btn.tag = UMSocialPlatformType_Sina;
        }
    }else{
        if(i==1){
            [btn setImage:[UIImage imageNamed:@"分享  复制链接"] forState:UIControlStateNormal];
            [btn setTitle:@"复制链接" forState:UIControlStateNormal];
            btn.tag = 11;
        }else if(i==2){
            [btn setImage:[UIImage imageNamed:@"分享 更多"] forState:UIControlStateNormal];
            
            [btn setTitle:@"更多分享" forState:UIControlStateNormal];
            btn.tag = 12;
        }else if(i==3){
            [btn setImage:[UIImage imageNamed:@"share_report"] forState:UIControlStateNormal];
            [btn setTitle:@"举报" forState:UIControlStateNormal];
            btn.tag = 13;
        }else if(i==4){
            [btn setImage:[UIImage imageNamed:@"share_del"] forState:UIControlStateNormal];
            [btn setTitle:@"删除" forState:UIControlStateNormal];
            btn.tag = 14;
        }
    }
}


-(void)shareWithButton:(UIButtonUpDown *) shareButton{
    if(shareButton.tag > 10){
        [self actionButton:shareButton];
        return;
    }
    
    UMSocialPlatformType shareType = shareButton.tag;
    
    if(shareType == UMSocialPlatformType_WechatSession || shareType == UMSocialPlatformType_WechatTimeLine){
        [self shareWeixinClick:shareButton];
        return;
    }
    
    NSDictionary *shareMessageDict = [self getShareMessage];
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    NSString *action = convertToString(shareMessageDict[@"action"]);
    
    messageObject.text = convertToString(shareMessageDict[@"desc"]);
    messageObject.title = convertToString(shareMessageDict[@"title"]);
    
    if(convertToString(shareMessageDict[@"url"]).length > 0){
        UMShareWebpageObject *shareObject = [[UMShareWebpageObject alloc] init];
        shareObject.title = convertToString(shareMessageDict[@"title"]);
        shareObject.descr = convertToString(shareMessageDict[@"desc"]);
        shareObject.thumbImage = shareImage;
        shareObject.webpageUrl = convertToString(shareMessageDict[@"url"]);
        
        // 必须为视频
        messageObject.shareObject = shareObject;
    }else{
        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
        shareObject.shareImage = shareImage;
        shareObject.title = convertToString(shareMessageDict[@"title"]);
        shareObject.descr = convertToString(shareMessageDict[@"desc"]);
        shareObject.thumbImage = shareImage;
        
        // 必须为视频
        messageObject.shareObject = shareObject;
    }
    
    
    

    messageObject.moreInfo = @{@"action":action};
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:shareType messageObject:messageObject currentViewController:_curVC completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
            [_curVC.view makeToast:@"分享失败！"];
        }else{
            NSLog(@"response data is %@",data);
            //            [_curVC.view makeToast:@"分享成功！"];
        }
    }];
    
    if(![[UMSocialManager defaultManager] isInstall:shareType]){
        [self dissmisMenu];
    }
}

-(NSDictionary *) getShareMessage{
    NSString *title = @"";
    NSString *content = @"";
    NSString *url = @"";
    NSString *action = @"";
    if(_type == ZZShareTypeTopic){
        ZZHomeTopicEntity *topic = _shareModel;
        title = convertToString(topic.title).length > 0 ? convertToString(topic.title):convertToString(topic.message_1);
        content = @"";
        url = convertToString(topic.share_url);
        action = [NSString stringWithFormat:@"qzonecc://topic?topicId=%zd",topic.t_id];
        
        UIImage *thumbImage = [UIImage imageNamed:@"icon_app"];
        shareImage = thumbImage;
        
        NSMutableArray *imgsObj = topic.images;
        if(imgsObj.count>0){
            ImageEntity *firstObj = [imgsObj firstObject];
            UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:convertToString(firstObj.image_url)];
      
            if(cachedImage!=nil){
                CGSize newsize = CGSizeMake(100, 100);
                UIGraphicsBeginImageContext(newsize);
                [cachedImage drawInRect:CGRectMake(0, 0, 100, 100)];
                UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                
                shareImage = [UIImage imageWithData:UIImagePNGRepresentation(newImage)];
            }
        }
    }
    
    if(_type == ZZShareTypeTiezi){
        ForumEntity *topic = _shareModel;
        title = convertToString(topic.title);
        content = convertToString(topic.message);
        url = convertToString(topic.share_url);
        action = [NSString stringWithFormat:@"qzonecc://topic?sid=%@",topic.thread_id];
        
        UIImage *thumbImage = [UIImage imageNamed:@"icon_app"];
        shareImage = thumbImage;
        
        NSMutableArray *imgsObj = topic.images;
        if(imgsObj.count>0){
            ImageEntity *firstObj = [imgsObj firstObject];
            UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:convertToString(firstObj.image_url)];
            
            if(cachedImage!=nil){
                CGSize newsize = CGSizeMake(100, 100);
                UIGraphicsBeginImageContext(newsize);
                [cachedImage drawInRect:CGRectMake(0, 0, 100, 100)];
                UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                
                shareImage = [UIImage imageWithData:UIImagePNGRepresentation(newImage)];
            }
        }
    }
    
    if(_type == ZZShareTypeSpecial){
        SpecialEntity *topic = _shareModel;
        title = convertToString(topic.title);
        content = convertToString(topic.intro);
        url = convertToString(topic.share_url);
        action = [NSString stringWithFormat:@"qzonecc://topic?sid=%@",topic.s_id];
        
        UIImage *thumbImage = [UIImage imageNamed:@"icon_app"];
        shareImage = thumbImage;
        
        UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:convertToString(topic.image_url)];
        
        if(cachedImage!=nil){
            CGSize newsize = CGSizeMake(100, 100);
            UIGraphicsBeginImageContext(newsize);
            [cachedImage drawInRect:CGRectMake(0, 0, 100, 100)];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            
            shareImage = [UIImage imageWithData:UIImagePNGRepresentation(newImage)];
        }
        
    }
    
    if(_type == ZZShareTypeApp){
        AppEntity *entity = _shareModel;
        title = convertToString(entity.app_name);
        content = convertToString(entity.app_desc);
        url = convertToString(entity.download_url);
        action = [NSString stringWithFormat:@"ccqzone://openapp"];
        
        UIImage *thumbImage = [UIImage imageNamed:@"icon_app"];
        shareImage = thumbImage;
    }
    if(_type == ZZShareTypeImage){
        AppEntity *entity = [ZZCoreTools getCoreTools].appEntity;
        title = convertToString(entity.app_name);
        content = convertToString(entity.app_desc);
        url = @"";//convertToString(entity.download_url);
        action = [NSString stringWithFormat:@"ccqzone://openapp"];
        
        UIImage *thumbImage = _shareModel;
        shareImage = thumbImage;
    }
    
    
    return @{@"title":title,
             @"desc":content,
             @"url":convertToString(url),
             @"action":action
             };
}


-(void)shareWeixinClick:(UIButtonUpDown *) shareButton{
    
    
    Byte* pBuffer = (Byte *)malloc(1024*100);
    memset(pBuffer, 0, 1024*100);
    NSData* data = [NSData dataWithBytes:pBuffer length:1024*100];
    free(pBuffer);
    
    static NSString *kAppMessageAction = @"<action>ccqzone</action>";
    WXAppExtendObject *ext = [WXAppExtendObject object];
    ext.extInfo = @"<xml>extend info</xml>";
    ext.url = @"http://weixin.qq.com";
    ext.fileData = data;
    
    
    NSDictionary *shareMessageDict = [self getShareMessage];
    
    //分享网页给好友
    WXMediaMessage *message = [WXMediaMessage message];
    message.description = shareMessageDict[@"desc"];
    message.mediaObject = ext;
    message.messageExt = shareMessageDict[@"action"];
    message.messageAction = kAppMessageAction;
    message.mediaTagName = nil;
    [message setThumbImage:shareImage];
    
    if(convertToString(shareMessageDict[@"url"]).length > 0){
        WXWebpageObject *webObject = [WXWebpageObject object];
        webObject.webpageUrl = shareMessageDict[@"url"];
        
        message.mediaObject = webObject;
    }else{
        WXImageObject *imageObject = [WXImageObject object];
        imageObject.imageData = UIImageJPEGRepresentation(shareImage, 1.0);
        message.mediaObject = imageObject;
    }
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.scene = WXSceneSession;
    if(shareButton.tag == 2){
        //分享网页到朋友圈
        req.scene = WXSceneTimeline;
    }
    
    [WXApi sendReq:req];
    [self dissmisMenu];
}


-(void)actionButton:(UIButtonUpDown *) shareButton{
    int tag = (int)shareButton.tag;
    
    // 复制链接
    if(tag == 11){
        
    }
    // 分享更多
    if(tag == 12){
        NSString *shareText = @"sharetitle";
        UIImage *shareImage = [UIImage imageNamed:@"167x167.png"];
        NSURL *shareURL = [NSURL URLWithString:@"https://www.baidu.com/"];
        NSArray *activityItems = [[NSArray alloc] initWithObjects:shareText, shareImage, shareURL, nil];
        
        UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
        
        UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
            NSLog(@"%@",activityType);
            if (completed) {
                NSLog(@"分享成功");
            } else {
                NSLog(@"分享失败");
            }
            [vc dismissViewControllerAnimated:YES completion:nil];
        };
        
        vc.completionWithItemsHandler = myBlock;
        
        [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
        
        [self dissmisMenu];
    }

//    if(tag == 12){
//        NSString *url = @"";
//        if(_type == ZZShareTypeKnowledge){
//            KnowledgeDetail *obj = (KnowledgeDetail *)_shareModel;
//            url = obj.url;
//        }else{
//
//            CommunityDetail *obj = (CommunityDetail *)_shareModel;
//            url = obj.url;
//        }
//        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
//        pasteboard.string = convertToString(url);
//        [PopUtil showMessage:@"已复制!" positionType:PopPositionTypeMiddle];
//    }
//    if(tag == 13){
//        NSInteger uuid = 0;
//        if(_type == ZZShareTypeKnowledge){
//            KnowledgeDetail *obj = (KnowledgeDetail *)_shareModel;
//            uuid = obj.uuid;
//        }else{
//            CommunityDetail *obj = (CommunityDetail *)_shareModel;
//            uuid = obj.uuid;
//        }
//        ReportView *report = [[ReportView alloc] initWithShareType:_curVC];
//        report.uuid = uuid;
//        [report show];
//    }
//    if(tag == 14){
//        if(_type == ZZShareTypeCommunity){
//            CommunityDetail *obj = (CommunityDetail *)_shareModel;
//
//            [NetworkUtil POST:kPostDelete parameters:@{@"id":convertIntToString((int)obj.uuid)} success:^(id responseObject) {
//                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//                if ([dictionary[@"code"] integerValue] == kNetworkSuccessCode) {
//                    [PopUtil showMessage:@"已删除!" positionType:PopPositionTypeMiddle];
//                    shareButton.hidden = YES;
//
//                    if(_ZZResultBlock){
//                        _ZZResultBlock(4);
//                    }
//
//                    [self dissmisMenu];
//                }
//                else{
//                    [PopUtil showMessage:dictionary[@"message"] positionType:PopPositionTypeMiddle];
//                }
//            } failure:^(NSError *error) {
//
//            }];
//        }
//    }
}


- (void)dissmisMenu{
    CGRect sheetViewF = self.frame;
    sheetViewF.origin.y = SCREEN_HEIGHT;
    self.backgroundColor = UIColor.clearColor;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.alpha = 0.0;
        self.frame = sheetViewF;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)show{
    CGRect sheetViewF = self.frame;
    sheetViewF.origin.y = 0;
    self.frame = sheetViewF;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = sheetViewF;
        self.backgroundColor = UIColorFromRGBAlpha(TextBlackColor, 0.4);
    } completion:^(BOOL finished) {
        
    }];
}

@end
